﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.Data;
using Maticsoft.DBUtility;
using System.Data.OracleClient;
using Xiaov.SmartWeb.Application.Models;

namespace Xiaov.SmartWeb.Application.SZBB
{
  public partial class InitTable : System.Web.UI.Page
  {
    private string tableName = "", dwbm = "", nf = "", yf = "";
    XMLVERSION modelXml = new XMLVERSION();

    protected void Page_Load(object sender, EventArgs e)
    {
      if (Request.QueryString["tableName"] != null || Request.QueryString["dwbm"] != null ||
        Request.QueryString["nf"] != null || Request.QueryString["yf"] != null)
      {
        tableName = Request.QueryString["tableName"].ToString();
        dwbm = Request.QueryString["dwbm"].ToString();
        nf = Request.QueryString["nf"].ToString();
        yf = Request.QueryString["yf"].ToString();
        InitVersion();
        string xml = GetXML();
        Response.Write(xml);
      }
      else
      {
        Response.Write("");
      }
    }

    private void InitVersion()
    {
      string sql = "select * from xmlversion where year=:0 and bbbm=:1";
      OracleParameter[] parms = { new OracleParameter(":0", OracleType.VarChar, 10), new OracleParameter(":1", OracleType.VarChar, 20) };
      parms[0].Value = nf;
      parms[1].Value = tableName;
      DataTable dt = DbHelperOra.Query(sql, parms).Tables[0];
      if (dt.Rows.Count == 1)
      {
        modelXml.SELECTFIELD = dt.Rows[0]["selectfield"].ToString();
        modelXml.CAPTION = dt.Rows[0]["caption"].ToString();
        modelXml.COORDINATES = dt.Rows[0]["coordinates"].ToString();
        modelXml.COLUMNCOUNT = int.Parse(dt.Rows[0]["columncount"].ToString());
        modelXml.ROWCOUNT = int.Parse(dt.Rows[0]["rowcount"].ToString());
        modelXml.Title = dt.Rows[0]["title"].ToString();
        modelXml.HIDDENCOLUMN = dt.Rows[0]["hiddencolumn"].ToString();
      }
    }

    private string GetXML()
    {
      StringBuilder xml = new StringBuilder();
      //string[] columnList = GetColumnName("CL0018");
      //string[] captionList = "单位编码,指标编码,年份,月份,指标名称,层级,行次,指标代码,计量单位,启用禁用,显示隐藏,是否可编辑,是否末级,本月止累计,国内,国外小计,去年同期,Rowid,小计,石化集团内,石化集团外".Split(new char[] { ',' });
      //string[] coorList = "0,1,0,2|1,1,0,2|2,1,0,2|3,1,0,2|4,1,0,2|5,1,0,2|6,1,0,2|7,1,0,2|8,1,0,2|9,1,0,2|10,1,0,2|11,1,0,2|12,1,0,2|13,1,0,2|14,3,0,1|17,1,0,2|18,1,0,2|19,1,0,2|14,1,1,1|15,1,1,1|16,1,1,1".Split(new char[] { '|' });
      //string[] captionList = "单位编码,指标编码,年份,月份,指标名称,层级,行次,指标代码,计量单位,启用禁用,显示隐藏,是否可编辑,是否末级,合计,国内小计,石化集团内,石化集团外,国 外,其中：待命,Rowid,小计,胜利,中原,河南,江汉,江苏,上海,华北,西南,华东,西北,东北,勘探南方,其他,小计,非洲,美洲,南亚及东南亚,中东,中亚及俄罗斯,其他".Split(new char[] { ',' });
      //string[] coorList = "0,1,0,2|1,1,0,2|2,1,0,2|3,1,0,2|4,1,0,2|5,1,0,2|6,1,0,2|7,1,0,2|8,1,0,2|9,1,0,2|10,1,0,2|11,1,0,2|12,1,0,2|13,1,0,2|14,1,0,2|15,14,0,1|29,1,0,2|30,7,0,1|37,1,0,2|38,1,0,2|15,1,1,1|16,1,1,1|17,1,1,1|18,1,1,1|19,1,1,1|20,1,1,1|21,1,1,1|22,1,1,1|23,1,1,1|24,1,1,1|25,1,1,1|26,1,1,1|27,1,1,1|28,1,1,1|30,1,1,1|31,1,1,1|32,1,1,1|33,1,1,1|34,1,1,1|35,1,1,1|36,1,1,1".Split(new char[] { '|' });

      xml.Append("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
      xml.Append("<Report>");
      xml.Append("<WorkSheet name=\"" + modelXml.Title + "\" isDefaultPrint=\"true\" FreezeCol=\"6\" FreezeRow=\"" + modelXml.ROWCOUNT + "\">");
      xml.Append(" <Fonts><Font faceName=\"宋体\" charSet=\"134\" height=\"-14\" weight=\"400\"/></Fonts>");
      xml.Append(@"
             <Properties SeparateBar=""zbmc"">
              <BackGround bgColor=""#FFFFFF"" /> 
             <DefaultTD>
                    <TD fontIndex=""0"" transparent=""true"" leftBorder=""0"" topBorder=""0"" leftBorderColor=""#C0C0C0"" leftBorderStyle=""solid"" topBorderColor=""#C0C0C0"" topBorderStyle=""solid"" decimal=""2"" align=""center"" vAlign=""middle"" isProtected=""false"" isThousandSeparat=""true"" isRound=""true"" isPrint=""true""/>
                  </DefaultTD>
                  <Other isShowZero=""true"" isRefOriPrecision=""true"" LineDistance=""0"" isRowHeightAutoExtendAble=""true"" isUsingEditMask=""true""/>
              </Properties>
            ");
      string header = GetHeaderXml();
      xml.Append(header);
      string data = GetDataXml();
      xml.Append(data);
      //xml.Append("<TR>");
      //for (int i = 0; i < modelXml.COLUMNCOUNT; i++)
      //{
      //  xml.Append("<td  leftBorder=\"0\" topBorder=\"1\"/>");
      //}
      //xml.Append("</TR>");
      xml.Append("</Table>");
      string merge = GetMergeXml();
      xml.Append(merge);
      //      xml.Append(@"<Validations>
      //      <Validation errorText=""钢材指标未填写!"" id=""C6"" title=""0"" icon=""730"">C6</Validation>
      //      <Validation errorText=""铝材指标未填写!"" id=""C7"" title=""0"" icon=""730"">C7</Validation>
      //      <Validation errorText=""铜材指标未填写!"" id=""C8"" title=""0"" icon=""730"">C8</Validation>
      //    </Validations>");
      xml.Append("</WorkSheet>");
      xml.Append(GetPringeXml());
      xml.Append("</Report>");
      return xml.ToString();
    }

    private string GetHeaderXml()
    {
      StringBuilder xml = new StringBuilder();
      string[] coorList = modelXml.COORDINATES.Split(new char[] { '|' });
      string[] captionList = modelXml.CAPTION.Split(new char[] { ',' });
      string[] hiddenCol = modelXml.HIDDENCOLUMN.Split(new char[] { ',' });
      xml.Append("<Table>");
      for (int i = 0; i < modelXml.COLUMNCOUNT; i++)
      {
        if (i == 4)
        { xml.Append("<Col width=\"260\" />"); }
        else
        {
          if (hiddenCol.Contains(i.ToString()))
          { xml.Append("<Col width=\"100\" isHide=\"true\" id=\"zbmc\"/>"); }
          else
          { xml.Append("<Col width=\"100\" datatype=\"double\"/>"); }
        }
      }
      xml.Append("<Col width=\"10\"/>");

      for (int row = 0; row < modelXml.ROWCOUNT; row++)
      {
        xml.Append("<TR>");
        for (int col = 0; col < modelXml.COLUMNCOUNT; col++)
        {
          xml.Append("<TD align=\"center\" bgColor=\"#E0E0E0\"  leftBorder=\"1\" topBorder=\"1\">");
          for (int i = 0; i < coorList.Length; i++)
          {
            string[] parent = coorList[i].Split(new char[] { ',' });
            int px = int.Parse(parent[0].ToString());
            int pxSpan = int.Parse(parent[1].ToString());
            int py = int.Parse(parent[2].ToString());
            int pySpan = int.Parse(parent[3].ToString());
            if (px == col && py == row) //当行尾时
            {
              string caption = captionList[i];
              xml.Append(caption);
              break;
            }
          }
          xml.Append("</TD>");
        }
        xml.Append("<TD leftBorder=\"1\" topBorder=\"0\"></TD>");
        xml.Append("</TR>");
      }
      return xml.ToString();
    }

    private string GetDataXml()
    {
      StringBuilder strSql = new StringBuilder();
      strSql.Append("select ");
      strSql.Append(modelXml.SELECTFIELD);
      strSql.Append(" FROM  ");
      strSql.Append(tableName);
      strSql.Append(" where dwbm=:0 and nf=:1 and yf=:2 ");
      OracleParameter[] parms = { new OracleParameter(":0", OracleType.VarChar, 10), new OracleParameter(":1", OracleType.VarChar, 20),
                                new OracleParameter("2",OracleType.VarChar,10)};
      parms[0].Value = dwbm;
      parms[1].Value = nf;
      parms[2].Value = yf;
      DataSet ds = DbHelperOra.Query(strSql.ToString(), parms);

      StringBuilder xml = new StringBuilder();
      string[] columnList = modelXml.SELECTFIELD.Split(new char[] { ',' });
      Dictionary<string, ENCO_BBZD> dicBBZD = GetBBZD();
      foreach (DataRow dr in ds.Tables[0].Rows)
      {
        xml.Append("<TR>");
        for (int i = 0; i < columnList.Length - 1; i++)
        {
          string zd = columnList[i].Trim();
          string value = dr[zd].ToString();
          if (zd == "ZBMC")
          {
            int cj = int.Parse(dr["cj"].ToString());
            for (int cjInd = 1; cjInd < cj; cjInd++)
            {
              value = "  " + value;
            }
          }
          if (zd == "ZBMC" || zd == "JLDW" || zd == "ZBDM")
          {
            xml.Append("<TD align=\"left\" bgColor=\"#E3E3E3\"  leftBorder=\"1\" topBorder=\"1\">");
            xml.Append(value);
            xml.Append("</TD>");
          }
          else
          {
            xml.Append("<TD align=\"left\" leftBorder=\"1\" topBorder=\"1\" ");
            ENCO_BBZD model = dicBBZD[zd];
            if (model.SJLX == "字符型")
            { xml.Append(" tabOrder=\"10\">"); }
            else
            { xml.Append(" tabOrder=\"10\">"); }
            xml.Append(value);
            xml.Append("</TD>");
          }
        }
        xml.Append("<TD leftBorder=\"1\" topBorder=\"0\"></TD>");
        xml.Append("</TR>");
      }
      xml.Append("<TR>");
      for (int i = 0; i < columnList.Length - 1; i++)
      {
        xml.Append("<TD topBorder=\"1\">");
        xml.Append("</TD>");      
      }
      xml.Append("</TR>");
      return xml.ToString();
    }

    private string GetMergeXml()
    {
      StringBuilder xml = new StringBuilder();
      string[] coorList = modelXml.COORDINATES.Split(new char[] { '|' });
      string[] captionList = modelXml.CAPTION.Split(new char[] { ',' });
      xml.Append("<Merges>");
      for (int i = 0; i < coorList.Length; i++)
      {
        string caption = captionList[i];
        string[] parent = coorList[i].Split(new char[] { ',' });
        int px = int.Parse(parent[0].ToString());
        int pxSpan = int.Parse(parent[1].ToString());
        int py = int.Parse(parent[2].ToString());
        int pySpan = int.Parse(parent[3].ToString());
        if (pxSpan > 1 || pySpan > 1) //当合并时
        {
          xml.Append("<Range row1=\"" + py + "\" col1=\"" + px + "\" row2=\"" + (py + pySpan - 1) + "\" col2=\"" + (px + pxSpan - 1) + "\"/>");
        }
      }
      xml.Append("</Merges>");
      return xml.ToString();
    }

    private string GetPringeXml()
    {
      StringBuilder xml = new StringBuilder();
      xml.Append(@"
    <PrintPage>
      <Paper>
        <Margin left=""19"" top=""25"" right=""19"" bottom=""25""/>
      </Paper>
    </PrintPage>");
      return xml.ToString();
    }

    private Dictionary<string, ENCO_BBZD> GetBBZD()
    {
      StringBuilder strSql = new StringBuilder();
      strSql.Append("select BBBM,ZD,ZDZS,SJLX,SJCD,SJJD,ZDSX,FLYC ");
      strSql.Append(" FROM ENCO_BBZD ");
      strSql.Append(" where bbbm='" + tableName + "'");
      DataTable dt = DbHelperOra.Query(strSql.ToString()).Tables[0];
      Dictionary<string, ENCO_BBZD> dicBBZD = new Dictionary<string, ENCO_BBZD>();
      for (int i = 0; i < dt.Rows.Count; i++)
      {
        ENCO_BBZD model = new ENCO_BBZD();
        model.BBBM = tableName;
        model.ZD = dt.Rows[i]["zd"].ToString();
        model.SJLX = dt.Rows[i]["sjlx"].ToString();
        dicBBZD.Add(model.ZD, model);
      }
      return dicBBZD;
    }
  }
}